<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="form" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="样本编号">
          <el-input v-model="queryParams.keywords" placeholder="样本编号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item prop="status" label="审核状态">
          <el-select v-model="queryParams.status" placeholder="审核状态" @change="updateStatus">
            <el-option label="未审核" value="REPORT_AUDIT"></el-option>
            <el-option label="审核完成" value="COMPLETED"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="el-icon-search">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <!-- <template #header>
                <el-button type="success" @click="openDialog()"><i class="el-icon-circle-plus"></i> 新增</el-button>
                <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i class="el-icon-delete"></i>
                    删除</el-button>
            </template> -->

      <el-table v-loading="loading" :data="dataList" highlight-current-row border :cell-style="cellStyle"
        @cell-click="openDetail" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" width="55" prop="dataIndex" />
        <el-table-column label="样本编号" prop="number" />
        <el-table-column label="样本状态" prop="statusText" />
        <el-table-column label="审核结果" prop="auditPassText" />
        <el-table-column label="创建时间" prop="createTimeText" />
        <el-table-column label="更新时间" prop="updateTimeText" />
        <el-table-column fixed="right" label="操作" min-width="320" width="320">
          <template #default="scope">
            <!-- <el-button type="warning" size="small" link
              @click="openDialog(scope.row.id)"><i class="el-icon-edit"></i> 编辑</el-button> -->
            <el-button type="warning" size="small" link @click="openBindSampleDialog(scope.row)"
              v-if="scope.row.status == 'CREATE'">绑定样本</el-button>
            <el-button type="primary" size="small" link @click="openExpressDialog(scope.row)"
              v-if="scope.row.status == 'TO_BE_SENT_OUT'">呼叫快递</el-button>
            <el-button type="warning" size="small" link @click="cancelExpress(scope.row)"
              v-if="scope.row.status == 'SENT_OUT'">取消快递</el-button>
            <el-button type="primary" size="small" link @click="labSignDialog(scope.row)"
              v-if="scope.row.status == 'SENT_OUT'">实验室签收</el-button>

            <el-button type="primary" size="small" link @click="openUploadFastqDialog(scope.row)"
              v-if="scope.row.status == 'SAMPLE_RECEIVE'">上传fastq文件</el-button>
            <el-button type="info" size="small" link @click="openDataSyncDialog(scope.row)"
              v-if="scope.row.status == 'REPORT_SEQ_END'">模拟样本同步</el-button>
            <el-button type="info" size="small" link @click="openUploadReportDialog(scope.row)"
              v-if="scope.row.status == 'DATA_ANALYSIS'">模拟样本分析完成</el-button>
            <el-button type="primary" size="small" link @click="openAuditDialog(scope.row)"
              v-if="scope.row.status == 'REPORT_AUDIT'">{{ scope.row.auditPass != null ? '重新审核样本' :
                '审核样本' }}</el-button>
            <!-- <el-button type="info" size="small" link @click="goDesignReport(scope.row)"
                            v-if="scope.row.status == 'REPORT_UPLOADED'">设计样本报告</el-button> -->
            <!-- <el-button type="danger" size="small" link @click="handleDelete(scope.row.id)">删除</el-button> -->
            <!-- <el-button type="primary" size="small" link @click="viewFile(scope.row.id)">查看文件</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum" :page-sizes="[10, 20, 50, 100]" :page-size="10"
          layout="total, sizes, prev, pager, next, jumper" :total="total">
        </el-pagination>
      </div>
    </el-card>

    <el-dialog :visible.sync="detailDialog.visible" :title="detailDialog.title" width="500px"
      :before-close="closeDetailDialog">
      <div>
        <p><span>样本编号：</span><span>{{ checkedSample.number }}</span></p>
        <p style="margin-top: 8px;"><span>样本状态：</span><span>{{ checkedSample.statusText }}</span></p>
        <p style="margin-top: 8px;"><span>更新时间：</span><span>{{ checkedSample.updateTimeText }}</span></p>
        <p style="margin-top: 8px;"><span>创建时间：</span><span>{{ checkedSample.createTimeText }}</span></p>
        <img :src="sampleImgUrl" style="margin-top: 10px; width: 175px;" />
      </div>
    </el-dialog>

    <!-- 样本表单弹窗 -->
    <el-dialog :visible.sync="dialog.visible" :title="dialog.title" width="500px" :before-close="closeDialog">
      <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="样本编号" prop="number">
          <el-input v-model="formData.number" placeholder="请输入样本编号" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="bindSampleDialog.visible" title="绑定样本" width="500px" :before-close="closeBindSampleDialog">
      <el-form ref="sampleFormRef" :model="bindSampleFormData" :rules="rules" label-width="100px">
        <el-form-item label="用户手机号" prop="phone">
          <el-input v-model="bindSampleFormData.phone" placeholder="请输入用户手机号" />
        </el-form-item>
        <el-form-item label="需绑定用户" prop="sysUserId">
          <el-select v-model="bindSampleFormData.sysUserId" placeholder="请选择">
            <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="bindUser">绑 定</el-button>
          <el-button @click="closeBindSampleDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="notifyExpressSampleDialog.visible" title="呼叫快递" width="500px"
      :before-close="closeExpressDialog">
      <el-form ref="expressFormRef" :model="notifyExpressSampleFormData" :rules="rules" label-width="100px">
        <el-form-item label="发件人姓名" prop="name">
          <el-input v-model="notifyExpressSampleFormData.name" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="发件人电话" prop="phone">
          <el-input v-model="notifyExpressSampleFormData.phone" placeholder="请输入用户手机号" />
        </el-form-item>
        <el-form-item label="发件地址" prop="addr">
          <el-cascader :options="options" v-model="selectedOptions" @change="changeExpressArea"></el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="addrExt">
          <el-input v-model="notifyExpressSampleFormData.addr" type="textarea" :autosize="{ minRows: 4 }"
            placeholder="请输入详细地址" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="notifyExpress">绑 定</el-button>
          <el-button @click="closeExpressDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :visible.sync="uploadFastqDialog.visible" :title="uploadFastqDialog.title" width="500px"
      :before-close="closeUploadFastqDialog">
      <el-form ref="uploadFastqFormRef" :model="uploadFastqFormData" :rules="rules" label-width="120px">
        <el-form-item label="fastq1文件信息" prop="fastq1">
          <el-input v-model="uploadFastqFormData.fastq1" placeholder="请输入fastq1文件信息" />
        </el-form-item>
        <el-form-item label="fastq2文件信息" prop="fastq2">
          <el-input v-model="uploadFastqFormData.fastq2" placeholder="请输入fastq2文件信息" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="uploadFastq">确 定</el-button>
          <el-button @click="closeUploadFastqDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 审核样本 -->
    <el-dialog :visible.sync="auditDialog.visible" :title="auditDialog.title" width="500px"
      :before-close="closeAuditDialog">
      <el-form ref="auditFormRef" :model="auditFormData" :rules="rules" label-width="120px">
        <el-form-item label="问题描述" prop="auditResult" v-show="!auditPass">
          <el-input v-model="auditFormData.auditResult" type="textarea" :autosize="{ minRows: 8 }"
            placeholder="请输入问题描述" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="info" @click="auditPass = false" v-show="auditPass">存在问题</el-button>
          <el-button type="primary" @click="auditSample" v-show="auditPass">审核通过</el-button>
          <el-button type="primary" @click="auditSample" v-show="!auditPass">确 认</el-button>
          <el-button @click="closeAuditDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看文件 -->
    <el-dialog :visible.sync="viewFileVisible" title="查看文件" width="1500px">
      <div class="viewFileVisible_box">
        <div class="input_file">
          <div class="input_file_top">
            <h3>输入文件</h3>
            <el-button type="warning" @click="unloadInputFlie()">上传文件</el-button>
          </div>

          <el-table :data="inputFileData" border style="width: 100%" max-height="500">
            <el-table-column prop="path" label="文件路径"></el-table-column>
            <el-table-column prop="suffix" label="文件类型"></el-table-column>
          </el-table>
        </div>

        <div class="output_file">
          <div class="input_file_top">
            <h3>输出文件</h3>
            <el-button type="warning">上传文件</el-button>
          </div>
          <el-table :data="outputFileData" border style="width: 100%" max-height="500">
            <el-table-column prop="path" label="文件路径"></el-table-column>
            <el-table-column prop="suffix" label="文件类型"></el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
    <el-dialog width="400px" :visible.sync="uploadFileVisible" title="上传文件">
      <el-upload class="upload-dialog" ref="upload" :action="uploadAction" :show-file-list="false"
        :on-change="submitUpload" :on-success="uploadFileSuccess" :headers="headers" :auto-upload="false">
        <el-button slot="trigger" style="margin-left: 5px;" type="success">上传Excel文件</el-button>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
    </el-dialog>

    <el-dialog width="400px" :visible.sync="uploadReportPdfVisible" title="模拟上传样本报告">
      <p>此操作为模拟上传样本报告，真实环境中是由报告系统自动上传用户样本报告。该操作会导致样本状态变更，请谨慎操作！</p>
      <el-upload class="upload-dialog" ref="uploadReport" :action="uploadReportPdfAction" :show-file-list="false"
        :on-change="submitUploadReport" :on-success="uploadReportFileSuccess" :headers="headers" :auto-upload="false">
        <el-button slot="trigger" style="margin-left: 5px;" type="success">上传样本报告</el-button>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
    </el-dialog>

  </div>
</template>

<script>
import { Session } from '@/utils/storage'
import sampleApi from '@/api/aliyun/detection/sample'
import expressApi from '@/api/aliyun/detection/express'
import userApi from '@/api/system/user'
import { formatDate } from '@/utils/formatTime'
import { provinceAndCityData, regionData, codeToText } from 'element-china-area-data'

export default {
  name: 'labSampleIndex',
  data() {
    return {
      queryParams: {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
        statuses: ['REPORT_AUDIT', 'COMPLETED'],
        status: '',
      },
      total: 0,
      loading: false,
      dataList: [],
      ids: [],
      userList: [],
      dialog: {},
      formData: {},
      rules: {},

      detailDialog: {},
      checkedSample: {},
      sampleImgUrl: '',

      uploadFastqDialog: {},
      uploadFastqFormData: {},

      auditDialog: {},
      auditFormData: {},

      statusMap: {
        CREATE: '已创建',
        TO_BE_SENT_OUT: '待寄出',
        SENT_OUT: '已寄出',
        SAMPLE_RECEIVE: '样本已收到',
        REPORT_SEQ_END: '实验室测序完成',
        DATA_ANALYSIS: '数据分析中',
        REPORT_AUDIT: '样本审核中',
        COMPLETED: '完成',
      },

      bindSampleDialog: {},
      bindSample: {},
      bindSampleFormData: {},

      notifyExpressSampleDialog: {},
      notifyExpressSample: {},
      notifyExpressSampleFormData: {},

      expressBaseAddr: '',
      addrExtInfo: '',
      options: regionData,
      selectedOptions: [],

      auditPass: true,
      viewFileVisible: false,
      inputFileData: [],
      outputFileData: [],
      viewFileSampleId: "",
      uploadAction: '',
      uploadFileVisible: false,
      headers: {},

      uploadReportPdfVisible: false,
      uploadReportPdfAction: '',

    };
  },
  mounted() {
    this.headers = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    };
  },
  methods: {
    updateStatus() {
      this.handleQuery();
    },
    openDataSyncDialog(row) {
      this.$confirm('此操作为模拟数据同步，确认之后，样本状态将发生变更, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        sampleApi.mockSyncSample(row.id).then(res => {
          this.$message({ message: '模拟样本同步成功！', type: 'success' });
          this.handleQuery();
        })
      }).catch(() => {
        this.$message.error('已取消操作！');
      });
    },
    openUploadReportDialog(row) {
      this.uploadReportPdfVisible = true;
      this.uploadReportPdfAction = process.env.VUE_APP_FILE_API_PREV + '/sample/mock-upload-report/' + row.id;
    },
    uploadReportFileSuccess() {
      this.uploadReportPdfVisible = false;
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.handleQuery();
    },
    submitUploadReport() {
      this.$refs.uploadReport.submit();
    },
    // 查看文件
    viewFile(id) {
      this.viewFileSampleId = id;
      this.viewFileVisible = true;
      sampleApi.getFileList(this.viewFileSampleId).then(res => {
        let fileData = res.data;
        let outOutData = [];
        let inputData = [];
        fileData.forEach((i) => {
          if (i.fileType == "OUTPUT") {
            outOutData.push(i)
          }
          if (i.fileType == "INPUT") {
            inputData.push(i);
          }
        })
        this.outputFileData = outOutData;
        this.inputFileData = inputData;
      })
    },
    unloadInputFlie() {
      this.uploadFileVisible = true;
    },
    submitUpload() {
      this.$refs.upload.submit();
    },
    uploadFileSuccess() {
      this.uploadFileVisible = false;
      this.$message({ message: '文件上传成功！', type: 'success' });
      this.handleQuery();
    },
    auditSample() {
      let auditPass = this.auditPass;
      sampleApi.auditSample({
        id: this.checkedSample.id,
        auditPass: auditPass,
        auditResult: this.auditFormData.auditResult,
      }).then(res => {
        this.$message({ message: '样本审核完成！', type: 'success' });
        this.$set(this.auditDialog, 'visible', false);
        this.handleQuery();
      })
    },
    openAuditDialog(row) {
      this.$set(this.auditDialog, 'visible', true);
      this.$set(this.auditDialog, 'title', '审核样本');
      this.checkedSample = row;
    },
    closeAuditDialog() {
      this.$set(this.auditDialog, 'visible', false);
    },
    uploadFastq() {
      let uploadFastqFormData = this.uploadFastqFormData;
      uploadFastqFormData.id = this.checkedSample.id;
      sampleApi.uploadSampleFastq(uploadFastqFormData).then(res => {
        this.$message({ message: 'fastq文件上传成功！', type: 'success' });
        this.$set(this.uploadFastqDialog, 'visible', false);
        this.handleQuery();
      })
    },
    closeUploadFastqDialog() {
      this.$set(this.uploadFastqDialog, 'visible', false);
    },
    openUploadFastqDialog(row) {
      this.$set(this.uploadFastqDialog, 'visible', true);
      this.$set(this.uploadFastqDialog, 'title', '上传fastq文件');
      this.checkedSample = row;
    },
    goDesignReport(row) {
      let url = this.$router.resolve({
        path: "/reporting/reportDesign",
        query: { number: row.number }
      })
      window.open(url.href, '_blank');
    },
    openDetail(row, column) {
      if (column.property == "number") {
        this.$set(this.detailDialog, 'visible', true);
        this.$set(this.detailDialog, 'title', '样本详情');
        this.checkedSample = row;
        this.sampleImgUrl = 'https://w66h994817.zicp.fun/platform/aliyun-api/sample/gene-barcode/' + row.number
      }
    },
    labSignDialog(row) {
      sampleApi.signSample(row.number).then((res) => {
        this.$message({ message: '样本签收成功！', type: 'success' });
        this.handleQuery();
      });
    },
    cancelExpress(row) {
      expressApi.cancel(row.id).then(res => {
        this.$message({ message: '样本快递已取消成功！', type: 'success' });
        this.handleQuery();
      })
    },
    notifyExpress() {
      let params = {
        sampleId: this.notifyExpressSample.id,
        name: this.notifyExpressSampleFormData.name,
        phone: this.notifyExpressSampleFormData.phone,
        addr: this.expressBaseAddr + this.notifyExpressSampleFormData.addr,
        addrExtInfo: JSON.stringify(this.addrExtInfo),
      };
      expressApi.add(params).then(res => {
        this.$message({ message: '样本呼叫快递成功！', type: 'success' });
        this.$set(this.notifyExpressSampleDialog, 'visible', false);
        this.handleQuery();
      })
    },
    changeExpressArea(vals) {
      this.expressBaseAddr = codeToText[vals[0]] + codeToText[vals[1]] + codeToText[vals[2]];
      this.addrExtInfo = vals;
    },
    openExpressDialog(row) {
      this.notifyExpressSample = row;
      this.$set(this.notifyExpressSampleDialog, 'visible', true);
    },
    closeExpressDialog() {
      this.$set(this.notifyExpressSampleDialog, 'visible', false);
    },
    bindUser() {
      sampleApi.bindSysUser({
        number: this.bindSample.number,
        phone: this.bindSampleFormData.phone,
        sysUserId: this.bindSampleFormData.sysUserId,
      }).then(res => {
        this.$message({ message: '样本绑定成功！', type: 'success' });
        this.$set(this.bindSampleDialog, 'visible', false);
        this.handleQuery();
      })
    },
    openBindSampleDialog(row) {
      this.bindSample = row;
      this.$set(this.bindSampleDialog, 'visible', true);
    },
    closeBindSampleDialog() {
      this.$set(this.bindSampleDialog, 'visible', false);
    },
    handleQuery() {
      this.loading = true;
      let params = {
        number: this.queryParams.pageNum,
        size: this.queryParams.pageSize,
        statuses: this.queryParams.statuses,
      };
      if (this.queryParams.status) {
        params.statuses = [this.queryParams.status]
      }
      sampleApi.page(params).then((res) => {
        let data = res.data;
        let that = this;
        let index = 1
        data.content.forEach((v) => {
          v.createTimeText = formatDate(new Date(v.createTime), "YYYY-mm-dd HH:MM:SS")
          v.updateTimeText = formatDate(new Date(v.updateTime), "YYYY-mm-dd HH:MM:SS")
          v.statusText = this.statusMap[v.status];
          v.auditPassText = v.auditPass != null ? (v.auditPass ? '审核通过' : '审核不通过') : '-'
          v.dataIndex = index++;
        });
        this.dataList = data.content;

        this.total = data.count;
        this.loading = false;
      }).catch(() => { });
    },
    resetQuery() {
      this.queryParams = {
        keywords: '',
        pageNum: 0,
        pageSize: 10,
        statuses: ['REPORT_AUDIT', 'COMPLETED'],
        status: '',
      };
      this.handleQuery();
    },

    addOrUpdate() {
      let that = this;
      if (this.formData.id) {
        sampleApi.update(this.formData).then((res) => {
          this.$message({ message: '样本更新成功！', type: 'success' });
          that.closeDialog();
        });
      } else {
        sampleApi.add(this.formData).then((res) => {
          this.$message({ message: '样本添加成功！', type: 'success' });
          that.closeDialog();
        });
      }
    },
    openDialog(id) {
      sampleApi.add({}).then((res) => {
        this.$message({ message: '样本添加成功！', type: 'success' });
        this.handleQuery();
      });
      // this.$set(this.dialog, 'visible', true);
      // let that = this;
      // if (id) {
      //   this.$set(this.dialog, 'title', '编辑样本');
      //   sampleApi.get(id).then((res) => {
      //     let data = res.data;
      //     that.formData = data;

      //   });
      // } else {
      //   this.$set(this.dialog, 'title', '新增样本');
      //   that.formData = {};
      // }

    },
    closeDialog() {
      this.$set(this.dialog, 'visible', false);
      this.$set(this.dialog, 'title', '');
      this.handleQuery();
    },
    handleDelete(id) {
      if (id) {
        sampleApi.delete(id).then((res) => {
          this.$message({ message: '样本删除成功！', type: 'success' });
          this.handleQuery();
        });
      } else {
        this.$message.error('暂不支持批量删除样本！');
      }
    },
    closeDetailDialog() {
      this.$set(this.detailDialog, 'visible', false);
      this.$set(this.detailDialog, 'title', '');
    },
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.property == "number") {
        return {
          "cursor": "pointer"
        }
      }
    },
    handleSelectionChange(val) {
      this.ids = [];
      val.forEach(v => {
        this.ids.push(v.id);
      });
    },
    handleSelectionRoleChange(rows) {
      if (rows) {
        let arr = [];
        rows.forEach((v) => {
          arr.push(v.id);
        });
        this.selectRoleIdArr = arr;
      }
    },
    handleSizeChange(val) {
      this.queryParams.pageSize = val;
      this.handleQuery();
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.handleQuery();
    },
  },
  created() {
    userApi.list().then((res) => {
      let data = res.data;
      this.userList = data;
    })
    this.handleQuery();
  }
};
</script>

<style scoped>
.block {
  margin-top: 10px;
  float: right;
  margin-bottom: 10px;
}

.viewFileVisible_box {
  display: flex;
}

.input_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2% 1%;
  margin-right: 2%;
}

.input_file h3 {
  /* margin-bottom: 2%; */
}

.output_file {
  width: 50%;
  border: 1px solid #DCDFE6;
  padding: 2%;
}

.output_file h3 {
  /* margin-bottom: 2%; */
}

.input_file_top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2%;
}
</style>